<template>
  <div class="receipt-order-edit-wrapper app-container" style="margin-bottom: 60px" v-loading="loading">
    <el-card header="材料出库单">
      <el-row :gutter="10">
        <el-form ref="elForm" :model="headerList" :rules="rules" size="small" label-width="130px">

          <el-col :span="12">
            <el-form-item label="创建日期" prop="dbilldate">
              <el-date-picker v-model="headerList.dbilldate" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable :style="{ width: '100%' }">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发料仓库" prop="cwarehouseid">
              <el-select v-model="headerList.cwarehouseid" placeholder="请选择仓库" :style="{ width: '100%' }"
                @change="handleCwarehouseidChange">
                <el-option v-for="item in NccStockOptions" :key="item.index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请类型" prop="申请类型">
              <el-input v-model="headerList.申请类型" placeholder="请输入申请类型" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料员" prop="nccUser">
              <el-select v-model="headerList.nccUser" filterable placeholder="请选择NCC用户信息" clearable
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in NccUserOptions" :key="index" :label="item.label" :value="item.value"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料部门" prop="deptName">
              <el-select v-model="headerList.deptName" placeholder="请输入部门信息" clearable :style="{ width: '100%' }" remote
                :remote-method="searchSelectNccDept" :loading="loading" filterable>
                <el-option v-for="item in deptNameOptions" :key="item.pk" :label="item.name" :value="item.pk" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="vnote">
              <el-input v-model="headerList.vnote" placeholder="请输入备注" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量" prop="ntotalnum">
              <el-input v-model="headerList.ntotalnum" placeholder="请输入总数量" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求日期" prop="vdef3">
              <el-date-picker v-model="headerList.vdef3" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable :style="{ width: '100%' }">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单人" prop="billmaker">
              <el-input v-model="headerList.billmaker" placeholder="请输入制单人" clearable :style="{ width: '100%' }">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单日期" prop="dmakedate">
              <el-date-picker v-model="headerList.dmakedate" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable :style="{ width: '100%' }">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料信息" prop="materialName">
              <el-select v-model="headerList.materialName" placeholder="请选择物料信息" clearable :style="{ width: '100%' }"
                remote :remote-method="searchSelectNccMaterialCode" :loading="loading" filterable
                @change="handleMaterialChange">
                <el-option v-for="item in materialNameOptions" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-card>

    <!-- 表格部分 -->
    <el-card class="mt20">
      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">材料出库单</span></el-col>
        <el-col :span="1.5">
          <el-select v-model="modeType" placeholder="选择批号模式" clearable @change="handleModeTypeChange">
            <el-option label="等于任意一个" value="0"></el-option>
            <el-option label="等于" value="1"></el-option>
            <el-option label="不等于" value="2"></el-option>
            <el-option label="包含" value="3"></el-option>
            <el-option label="不包含" value="4"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-form ref="elForm" :rules="rules" size="small">
        <el-table :data="materialDetailsList" border @selection-change="handleTableSelectionChange" label-position="top"
          :row-key="row => row.id">
          <!-- 选择框列 -->
          <el-table-column type="selection" width="40" :reserve-selection="true" />
          <!-- <el-table-column label="批次号">
            <template #default="{ row }">
              <el-input v-model="row.vbatchcode" placeholder="请输入批次号" clearable size="small"></el-input>
            </template>
</el-table-column>

<el-table-column prop="nshouldnum" label="应发主数量">
  <template #default="{ row }">
              <el-input v-model="row.nshouldnum" placeholder="请输入主数量" clearable size="small"></el-input>
            </template>
</el-table-column> -->
          <el-table-column label="物料信息">
            <template #default="{ row }">
              <div>
                <div>物料名称：</div>
                <div>{{ row.name }}</div>
              </div>
              <div>
                <div>物料编码：</div>
                <div>{{ row.code }}</div>
              </div>
              <!-- <div>
                <div>物料PK：</div>
                <div>{{ row.pk_material }}</div>
              </div> -->
            </template>
          </el-table-column>
          <el-table-column label="库房信息">
            <template #default="{ row }">
              <div>
                <div>库房名称：</div>
                <div>{{ row.cwarehouse_name }}</div>
              </div>
              <div>
                <div>库房ID：</div>
                <div>{{ row.cwarehouse_id }}</div>
              </div>
              <div>
                <div>货位号：</div>
                <div>{{ row.sto_unit_id }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="规格批号信息">
            <template #default="{ row }">
              <div>
                <div>规格：</div>
                <div>{{ row.materialspec }}</div>
              </div>
              <div>
                <div>批号：</div>
                <div>{{ row.pk_batchcode }}</div>
              </div>
              <div>
                <div>供应商批号：</div>
                <!-- <div>{{ row.vbatchcode }}</div> -->
                <el-input v-model="row.vbatchcode" placeholder="请输入批次号" clearable size="small"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量信息">
            <template #default="{ row }">
              <div>
                <div>在途数量：</div>
                <div>{{ row.enable_num }}</div>
              </div>
              <div>
                <div>冻结数量：</div>
                <div>{{ row.freeze_num }}</div>
              </div>
              <div>
                <div>可用数量：</div>
                <div>{{ row.use_num }}</div>
              </div>
            </template>
          </el-table-column>
          <!-- 新增的NCC生产厂商信息和NCC供应商信息下拉选择框列 -->
          <el-table-column label="数量修改">
            <template #default="{ row }">
              <div>
                <div>应发主数量：</div>
                <el-input v-model="row.nshouldnum" placeholder="请输入主数量" clearable size="small"></el-input>
              </div>
              <div>
                <div>应发数量：</div>
                <el-input v-model="row.nshouldassistnum" placeholder="请输入数量" clearable size="small"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column :data="proList" label="NCC信息">
            <template #default="{ row }">
              <div prop="manufacturerName">
                <div>生产商:</div>
                <el-select v-model="row.manufacturerName" placeholder="请输入生产商" clearable :style="{ width: '100%' }"
                  remote :remote-method="searchSelectNccManufacturer" :loading="loading" filterable
                  @change="handleManufacturerNameChange">
                  <el-option v-for="item in manufacturerNameOptions" :key="item.pk" :label="item.name"
                    :value="item.pk" />
                </el-select>
              </div>
              <div prop="cstateid">
                <div>单据状态:</div>
                <el-select v-model="row.cstateid" placeholder="请选择下拉选择" :style="{ width: '100%' }">
                  <el-option v-for="item in NccStatusOptions" :key="item.index" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="日期信息" width="300">
            <template #default="{ row }">
              <div class="dateDiv">
                <span class="dateSpan">有 效 期</span>
                <el-date-picker v-model="row.exp_date" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable
                  :style="{ flex: '1', width: 'auto' }">
                </el-date-picker>
              </div>
              <div class="dateDiv">
                <span class="dateSpan">生产日期</span>
                <el-date-picker v-model="row.pd_date" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable
                  :style="{ flex: '1', width: 'auto' }">
                </el-date-picker>
              </div>
              <div class="dateDiv">
                <span class="dateSpan">复 验 期</span>
                <el-date-picker v-model="row.retest_date" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable
                  :style="{ flex: '1', width: 'auto' }">
                </el-date-picker>
              </div>
              <div class="dateDiv">
                <span class="dateSpan">订单日期</span>
                <el-date-picker v-model="row.drequiredate" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择日期" clearable
                  :style="{ flex: '1', width: 'auto' }">
                </el-date-picker>
              </div>
            </template>

          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button type="danger" size="small" plain @click="handleDeleteRow(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item size="large" style="margin-top: 20px; float: right;">
          <el-button type="primary" @click="createMaterialsOutboundList">提交</el-button>
          <!-- <el-button @click="resetForm">重置</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>

// 根据NCC物料主键获取物料详细信息接口
import { getSelectNccMaterialCode } from '@/api/supply/materialSupply.js'

// 新增材料出库单据接口
import { createMaterialsOutbound } from '@/api/supply/materialSupply.js'

// 根据获取NCC物料库存信息接口
import { getSelectNccMaterialInfo } from '@/api/public.js'

// 引入下拉框方法组件
import SearchSelect from '@/views/components/dropDown/searchSelect.js';

export default {
  data() {
    return {
      loading: false, // 控制加载状态
      selectedRow: null, // 当前选中的表格行
      tableRowChecked: [], // 用于记录每行的选中状态
      headerList: {
        cwarehouseid: '', // 用于绑定仓库信息下拉框选中的值
        nccUser: '', // 用于绑定NCC用户信息下拉框选中的值
        billmaker: '1001A11000000000W9B3',  // 制单人 固定值"1001A11000000000W9B3"
        creator: '1001A11000000000W9B3',  //制单人 固定值"1001A11000000000W9B3"
        deptName: '', // 部门名称
        ctrantypeid: '4D-Cxx-005',
        materialName: '',
        code: ''
      },
      NccStockOptions: [], // 搜索NCC仓库信息_1
      NccStatusOptions: [], // 获取NCC库存状态信息_2
      NccUserOptions: [], // 获取NCC用户信息_3
      deptNameOptions: [], // 获取NCC-普锐特部门信息_4
      manufacturerNameOptions: [], // 获取NCC生产厂商信息_6
      materialNameOptions: [], // 获取NCC物料信息-code_9
      materialDetailsList: [], // 将其初始化为数组，方便后续进行符合响应式的操作
      nccManuOptions: [], // 用来存放NCC生产厂商下拉框的选项数据
      nccSupplierOptions: [], // 用来存放NCC供应商下拉框的选项数据
      proList: {
        manufacturerName: '',
        cstateid: ''
      },
      rules: {
        // 这里根据实际的表单验证需求添加具体的验证规则，以下是示例，可按需调整
        nccUser: [
          { required: false, message: '请选择NCC用户信息', trigger: 'blur' }
        ],
        deptName: [
          { required: false, message: '请输入部门信息', trigger: 'blur' }
        ],
        materialName: [
          { required: false, message: '请输入物料信息', trigger: 'blur' }
        ],
        manufacturerName: [
          { required: false, message: '请输入生产厂商名称', trigger: 'blur' }
        ]
      },
      modeType: '0',
      // modeType: null, // 下拉框值，默认为空
      materialDetailsList: [], // 表格数据
      allMaterialDetailsList: [], // 初始获取的完整表格数据
    }
  },
  // created() {
  //   // 接收路由参数
  //   this.vbillcode = this.$route.query.vbillcode || '';
  //   if (!this.vbillcode) {
  //     this.$message.error('未收到订单编号，请返回重试！');
  //   }
  // },
  watch: {
    batchMode(newValue) {
      if (this.headerList.materialName) {
        this.fetchMaterialDetails(this.headerList.materialName);
      }
    }
  },
  mounted() {
    this.searchNCCStockList(); // 1、获取NCC仓库信息
    this.searchNCCStockStatusList(); // 2、获取NCC库存状态信息
    this.searchSelectNccUserList(); // 3、获取NCC用户信息
    // 初始加载数据（不带筛选）
    // this.fetchMaterialDetails("当前批次号"); // 示例批次号
  },
  methods: {
    /**
    * 处理删除行的操作
    */
    handleDeleteRow(rowToDelete) {
      // 判断selectedRow是否为null，如果是则赋值为空数组
      if (this.selectedRow === null) {
        this.selectedRow = [];
      }
      // 通过数组的 filter 方法，过滤掉要删除的行数据，得到新的数组，从而实现从列表中移除该行
      this.materialDetailsList = this.materialDetailsList.filter(row => row !== rowToDelete);
      // 更新tableRowChecked数组，保持每行选中状态与当前实际表格数据一致
      this.tableRowChecked = this.materialDetailsList.map(row => this.selectedRow.includes(row));
    },
    // 处理表格行选择事件
    handleTableSelectionChange(selectedRows) {
      // 根据传入的当前选中的行数据数组selectedRows，更新tableRowChecked数组来标记每行的选中状态
      this.tableRowChecked = this.materialDetailsList.map(row => selectedRows.includes(row));
      // 将当前选中的行数据整体赋值给selectedRow属性，方便在其他地方获取和使用选中行的详细数据（支持多选情况）
      this.selectedRow = selectedRows;
    },
    handleMaterialChange(selectedPk) {
      console.log('在handleMaterialChange中，selectedPk:', selectedPk);
      if (selectedPk) {
        // 获取物料详细信息
        this.fetchMaterialDetails(selectedPk);
        const selectedRows = this.materialDetailsList.filter((_, index) => this.tableRowChecked[index]);
        selectedRows.forEach(row => {
          row.code = selectedPk; // 将选择的物料主键值保存到对应的行对象中
        });
        console.log('在handleMaterialChange中，this.materialDetailsList:', this.materialDetailsList);
      }
    },
    handleWarehouseChange(cwarehouseid) {
      // 在这里添加根据仓库变化需要执行的业务逻辑
      console.log('选择的仓库值改变了:', cwarehouseid);
    },
    handleManufacturerNameChange(manufacturerName) {
      // 这里添加选择生产商后需要执行的逻辑
      console.log('选择的生产商值改变了:', manufacturerName);
    },

    /**
    * 新增材料出库单据
    */
    createMaterialsOutboundList() {
      // 开启加载状态提示
      this.loading = true;

      console.log('当前headerList.code的值为:', this.headerList.code);

      // 直接根据tableRowChecked数组筛选出选中行数据，即获取当前在表格中被用户勾选的行数据
      const selectedRows = this.materialDetailsList.filter((_, index) => this.tableRowChecked[index]);

      // 如果没有选中任何行，给出提示信息告知用户需要选择入库项，并关闭加载状态提示，直接返回不再继续后续操作
      if (!selectedRows.length) {
        this.$message.warning('请选择入库项');
        this.loading = false;
        return;
      }

      // 将选中行的数据进行整理，提取出需要传递给后端接口的各个字段信息，
      // 组成新的对象数组detailsData，应准确提取对应字段的值
      const detailsData = selectedRows.map(row => ({
        cmaterialvid: row.code, // 从每行数据对象里获取对应的物料code值
        nshouldnum: row.nshouldnum,
        nshouldassistnum: row.nshouldassistnum,
        cproductorid: row.manufacturerName,
        cstateid: row.cstateid,
        drequiredate: row.drequiredate,
        vbatchcode: row.vbatchcode
      }));

      console.log('材料出库，返回detailsData数据：', detailsData);

      // 构建表头信息对象header，包含入库单表头主键和仓库信息等关键表头数据，用于传递给后端接口
      const ic_material_h = {
        cwarehouseid: this.headerList.cwarehouseid,
        cbizid: this.headerList.nccUser,
        billmaker: this.headerList.billmaker,
        creator: this.headerList.creator,
        ctrantypeid: this.headerList.ctrantypeid,
      };

      console.log('材料出库，返回header数据：', ic_material_h);

      // 除了检查关键信息是否为空值，还可以添加一些更详细的表单验证逻辑，比如验证数据格式是否符合要求等
      const isValidHeader = ic_material_h.cwarehouseid &&
        ic_material_h.cbizid &&
        ic_material_h.billmaker &&
        ic_material_h.creator &&
        ic_material_h.ctrantypeid;

      if (!isValidHeader) {
        this.$message.error('请填写完整且正确的表头信息');
        this.loading = false;
        return;
      }

      // 将表头信息和整理好的商品明细信息整合到一个对象combinedData中
      const combinedData = { ic_material_h, ic_material_b: detailsData };

      createMaterialsOutbound(combinedData)
        .then(response => {
          console.log('接口请求成功，返回response数据：', response);

          this.loading = false;

          if (response.code === 200) {
            this.$message.success(response.msg);
            this.$tab.closePage(); // 关闭当前页面的标签
          } else {
            this.$message.error(response.msg);
          }
        })
        .catch(error => {
          this.loading = false;
          console.log('接口请求出错:', error);
        });
    },

    /**
     * 根据根据NCC物料code获取物料详细信息并更新表格数据
     */
    async fetchMaterialDetails(code) {
      try {
        const response = await getSelectNccMaterialCode(code);
        console.log('获取物料详细信息response:', response);

        // 提取基础字段
        const { code: batchNo, pk_material: primaryKey } = response.data;

        // 初始化请求参数（不传 modeType 时获取全部数据）
        const params = { batchNo, primaryKey };
        if (this.modeType !== null) {
          // 根据 modeType 设置筛选模式
          params.mode = this.getModeTypeString(this.modeType);
        }

        console.log("请求参数 params:", params);

        // 调用接口获取物料库存信息
        const infoResponse = await getSelectNccMaterialInfo(params);
        console.log("获取物料库存信息 infoResponse:", infoResponse);

        if (!infoResponse || !infoResponse.data) {
          throw new Error("物料库存接口返回的数据为空");
        }

        // 处理接口返回数据
        const processedData = infoResponse.data.map((item) => ({
          ...item,
          name: item.name || "未知物料名称",
          code: item.code || "未知编码",
          pk_material: item.pk_material || "未知PK",
          cwarehouse_id: item.cwarehouse_id || "", // 库房ID
          cwarehouse_name: item.cwarehouse_name || "未知库房", // 库房名称
          enable_num: item.enable_num || 0, // 在途数量
          exp_date: item.exp_date || null, // 有效期
          freeze_num: item.freeze_num || 0, // 冻结数量
          materialspec: item.materialspec || "未知规格", // 规格
          pd_date: item.pd_date || null, // 生产日期
          pk_batchcode: item.pk_batchcode || "", // 批号
          retest_date: item.retest_date || null, // 复验期
          sku_num: item.sku_num || 0, // 数量
          sto_unit_id: item.sto_unit_id || "", // 货位号
          use_num: item.use_num || 0, // 可用数量
          vbatchcode: item.vbatchcode || "", // 公因式批号
          vvendbatchcode: item.vvendbatchcode || "", // 供应商批号
        }));

        // 如果是初次加载，保存到全量数据和表格数据
        if (this.modeType === null) {
          this.allMaterialDetailsList = [...processedData];
        }

        // 更新表格数据
        this.materialDetailsList = processedData;

        console.log("更新后的 materialDetailsList:", this.materialDetailsList);
      } catch (error) {
        console.error("获取物料详细信息接口调用出错:", error);
        this.$message.error("获取物料详细信息接口调用出错，请稍后重试");
      }
    },

    // 根据 modeType 返回对应的模式字符串
    getModeTypeString(modeType) {
      switch (modeType) {
        case "0":
          return "any"; // 等于任意一个
        case "1":
          return "equal"; // 等于
        case "2":
          return "notEqual"; // 不等于
        case "3":
          return "contain"; // 包含
        case "4":
          return "notContain"; // 不包含
        default:
          return "any"; // 默认模式
      }
    },

    // 下拉框值变化时的逻辑处理
    handleModeTypeChange() {
      console.log("选择的批号模式:", this.modeType);

      // 如果未选择 modeType，则恢复全部数据
      if (this.modeType === 0) {
        this.materialDetailsList = [...this.allMaterialDetailsList];
        console.log("选择的materialDetailsList:", this.materialDetailsList);
      } else {
        // 根据 modeType 重新筛选并渲染表格
        this.fetchMaterialDetails("当前批次号"); // 示例批次号
      }
    },


    resetForm() {
      this.$refs.elForm.resetFields();
    },

    // 1、获取NCC仓库信息
    searchNCCStockList() {
      this.loading = true;
      SearchSelect.searchNCCStockList(this)
        .then(() => {
          // 获取到仓库信息后，更新 NccStockOptions
          this.NccStockOptions = this.NccStockList.map(item => ({
            label: item.label,
            value: item.value,
          }));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 2、获取NCC库存状态信息
    searchNCCStockStatusList() {
      this.loading = true;
      SearchSelect.searchNCCStockStatusList(this)
        .then(() => {
          // 获取到NCC库存状态信息后，更新 NccStatusOptions
          this.NccStatusOptions = this.NccStatusList.map(item => ({
            label: item.label,
            value: item.value,
          }));
        })
        .finally(() => {
          this.loading = false;
        });
    },


    // 3、获取NCC用户信息
    searchSelectNccUserList() {
      this.loading = true;
      SearchSelect.searchSelectNccUserList(this)
        .then(() => {
          // 获取到NCC库存状态信息后，更新 NccUserOptions
          this.NccUserOptions = this.NccUserList.map(item => ({
            label: item.label,
            value: item.value,
          }));
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 4、获取NCC-普锐特部门信息
    searchSelectNccDept(query) {
      SearchSelect.searchSelectNccDept(query, this);
    },
    // 6、获取NCC生产厂商信息
    searchSelectNccManufacturer(query) {
      SearchSelect.searchSelectNccManufacturer(query, this);
    },
    // 9、获取NCC物料信息-code
    searchSelectNccMaterialCode(query) {
      SearchSelect.searchSelectNccMaterialCode(query, this);
    },
  }
}
</script>

<style scoped>
.dateDiv {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.dateSpan {
  display: inline-block;
  width: 60px;
  /* 根据需要调整宽度 */
  margin-right: 10px;
  text-align: center;
  /* 如果需要文本居中 */
}
</style>